﻿using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using System;
using System.IO;

namespace AlarmClock.BLL
{
    public class PPNAudio : IMusicPlayer
    {
        private string path;
        private IWavePlayer _device;//设备
        private AudioFileReader _reader;
        private VolumeSampleProvider _volumeProvider;
        private bool RepeatMode = false;//重复播放
        private TimeSpan _duration => _reader.TotalTime;//总时长
        private TimeSpan _currentTime => _reader.CurrentTime;//当前播放事件

        public PPNAudio(string path)
        {
            try
            {
                if (!File.Exists(path))
                {
                    throw new FileNotFoundException($"文件：{path} 不存在！");
                }

                this.path = path;
                this._device = new WaveOutEvent();
                this._reader = new AudioFileReader(path);
                this._volumeProvider = new VolumeSampleProvider(_reader);
                this._device.Init(this._volumeProvider);
            }
            catch (Exception ex)
            {
                Service.ExceptionTraceLog(ex);
                throw ex;
            }
        }

        public static bool CanPlay(string musicPath)
        {
            try
            {
                _ = new PPNAudio(musicPath);
                return true;
            }
            catch 
            {
                return false;
            }
        }
        public void Pause()
        {
            this._device?.Pause();
        }

        public void Play()
        {
            this._device?.Play();
        }

        public void PlayRepeat()
        {
            RepeatMode = true;
            Play();
            this._device.PlaybackStopped += (s, e) => { if (RepeatMode) RePlay(); };
        }

        public void RePlay()
        {
            if (_reader != null) _reader.Position = 0;
            Play();
        }

        /// <summary>
        /// 设置音量（0.0-1.0）
        /// </summary>
        /// <param name="volume"></param>
        public void SetVolume(float volume)
        {
            if (this._device != null)
            {
                this._device.Volume = volume;
            }
        }

        public void Stop()
        {
            RepeatMode = false;
            Dispose();
        }

        public void Dispose()
        {
            _device?.Stop();
            _device?.Dispose();
            _reader?.Dispose();
        }



    }
}
